package cn.beetech.demo.digest;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.Console;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;

public class Digest {
    public static String objToString(Object v) {
        if (v instanceof int[]) {
            return Arrays.toString((int[]) v);
        }

        if (v instanceof String[]) {
            return Arrays.toString((String[]) v);
        }

        if (v instanceof double[]) {
            return Arrays.toString((double[]) v);
        }

        if (v instanceof float[]) {
            return Arrays.toString((float[]) v);
        }

        if (v instanceof long[]) {
            return Arrays.toString((long[]) v);
        }

        if (v instanceof short[]) {
            return Arrays.toString((short[]) v);
        }

        if (v instanceof byte[]) {
            return Arrays.toString((byte[]) v);
        }

        if (v instanceof boolean[]) {
            return Arrays.toString((boolean[]) v);
        }

        return v.toString();
    }

    public static String makeDigest(Map<String, Object> paramMap,
                                    String timestamp,
                                    String secret) {
        String sortValue = paramMap.entrySet().stream()
                .filter(e -> !e.getKey().equals("timestamp")
                        && !e.getKey().equals("digest")
                        && !e.getKey().equals("authorAgreementFile")
                        && e.getValue() != null
                        && !"".equals(e.getValue())
                        && !"null".equals(e.getValue()))
                .sorted(Comparator.comparing(Map.Entry::getKey))
                .map(Map.Entry::getValue)
                .reduce("", (a, b) -> a + objToString(b) + "_") + timestamp + "_" + secret;
        return DigestUtils.md5Hex(sortValue.getBytes()).toUpperCase();
    }
}